const mongoose = require("mongoose")
const Schema = mongoose.Schema;
mongoose.connect("mongodb://127.0.0.1/mongoose_test")
mongoose.connection.once("open", () => {
    console.log("mongodb已连接");
})
// mongoose.disconnect();
mongoose.connection.once("close", () => {
    console.log("mongodb已断开连接");
})
//  创建一个Schema约束对象
let friendsSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    age: {
        type: Number,
        default: 18
    },
    gender: {
        type: String,
        required: true,
    }
})
// 创建一个Model对象    mongoose(要映射到哪个集合中，使用哪个Schema约束对象)
let StudentsModel = mongoose.model("friends", friendsSchema)
// 这是即可通过Model对象，对数据库进行增删改查的操作了
// 增
// StudentsModel.create({ name: "hwj", age: 18, gender: "male" }).then(res => console.log(res))
// StudentsModel.insertMany([{ name: "hwj", age: 18, gender: "male" }, { name: "shh", age: 18, gender: "female" }]).then(res => console.log(res))
// 删
// StudentsModel.deleteOne({name:})
// 改
// StudentsModel.updateOne({ name: "hwj" }, { age: 20 }).then(res => console.log(res))
// StudentsModel.updateMany({ name: "hwj" }, { age: 20 }).then(res => console.log(res))
// 查
// StudentsModel.findOne({ name: "shh" })
// 参数projection的字符串写法
// StudentsModel.find({}, "name -_id age").then(res => console.log(res))
// 参数projection的对象写法
// StudentsModel.find({}, { name: 1, _id: 0 }).then(res => console.log(res))
// 参数options的使用
// StudentsModel.find({}, { name: 1, _id: 0, age: 1 }, { sort: { age: -1 }, skip: 1, limit: 2 }).then(res => console.log(res))

// StudentsModel.findOne({ name: "hwj" }).then(res => {
//     StudentsModel.findById(res._id, { name: 1, _id: 0 }).then(res => console.log(res))
// })

StudentsModel.count({}).then(res => console.log(res))